package net.vistiyos.android;

import java.util.ArrayList;

import net.vistiyos.R;
import net.vistiyos.busquedas.Buscar;
import net.vistiyos.exception.GetDataSerieException;
import net.vistiyos.exception.NotSignInException;
import net.vistiyos.modelo.Serie;

import org.w3c.dom.DOMException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;

public class PanelAdministracion extends Activity implements OnQueryTextListener{
	
	private ProgressDialog dialog;
	private SearchView searchView;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.paneladministracion);
		MyPagerAdapter adapter = new MyPagerAdapter(this);
		ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
		myPager.setAdapter(adapter);
		myPager.setCurrentItem(1);
	}
	
	@Override
	public void onResume(){
		super.onResume();
		MyPagerAdapter adapter = new MyPagerAdapter(this);
		ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
		myPager.setAdapter(adapter);
		myPager.setCurrentItem(1);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    getMenuInflater().inflate(R.menu.busqueda, menu);
	    searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
	    searchView.setOnQueryTextListener(this);
	    return super.onCreateOptionsMenu(menu);
	}

	public boolean onQueryTextChange(String newText) {
		return false;
	}

	public boolean onQueryTextSubmit(String query) {
		new ObtenerDatos().execute(query);
		return false;
	}
	
private class ObtenerDatos extends AsyncTask< String, Void, ArrayList<Serie>>{
		
		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(PanelAdministracion.this, "Progreso", "Buscando...Espere por favor");
		}
		
		@Override
		protected ArrayList<Serie> doInBackground(String... params) {
			try {
				Buscar.buscarSerie(params[0]);
			} catch	(NotSignInException e) {
				 e.printStackTrace();
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (DOMException e) {
				e.printStackTrace();
			} catch (GetDataSerieException e) {
				e.printStackTrace();
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(ArrayList<Serie> result) {
			if (dialog != null) {
				dialog.dismiss();
			}
			Intent busqueda = new Intent(PanelAdministracion.this,SearchActivity.class);
			PanelAdministracion.this.startActivity(busqueda);
		}
	}
}
